<?php
namespace app\gym\model;
use app\common\model\Base;
use think\Loader;
use think\Validate;
/**
 * [NutrtiousMeal 健身房营养餐的功能]
 */
class NutritiousMeal extends Base{
/**
 * `id` int(15) unsigned NOT NULL AUTO_INCREMENT COMMENT '自动增长id作为键使用',
 *`Ingredients` varchar(200) NOT NULL DEFAULT '' COMMENT '营养餐的主要成分输入的内容以,号进行分割',
 *  `create_time` int(15) unsigned NOT NULL COMMENT '创建时间',
 *  `last_update_time` int(15) unsigned NOT NULL COMMENT '最后修改时间',
 *  `picture` varchar(100) NOT NULL COMMENT '营养餐的图片',
 *  `nutrition` varchar(200) NOT NULL COMMENT '营养成分',
 *  `gym_id` char(64) NOT NULL COMMENT '健身房的编号',
 *  `which_day` int(1) unsigned NOT NULL COMMENT '哪一天（周几）', [$table description]
 * @var string
 */
  protected $table = 'gym_nutritious_meal';

  protected static $inputData = '';

  protected static $publicTool = null; //公共方法
  /**
   * [init 模型静态初始化]
   * @return [void] [此方法没有返回值]
   */
  public static function init(){
    //设置公共方法类
    self::$publicTool = Loader::controller('\\app\\publictool\\controller\\PublicTool');
  }


  /**
   * [push 添加营养餐中]
   * @return [type] [true|false 返回布尔类型的内容]
   */
  public static function push(){
    $inputData = self::getInputData();
    $allowField[] = 'ingredients'; //营养餐的成分
    $allowField[] = 'creat_time'; //创建时间
    $allowField[] = 'last_update_time'; //最后更新时间
    $allowField[] = 'picture'; //图片内容
    $allowField[] = 'nutrition'; //营养成分
    $allowField[] = 'gym_id'; //健身房的编号
    $allowField[] = 'which_day';//一周中的哪一天
    $validate = new Validate(
      [
        'ingredients'=>'require',
        'picture'=>'require',
        'nutrition'=>'require',
        'gym_id'=>'require',
        'which_day'=>'require|number'
      ],
      [
        'ingredients.require'=>'营养餐的成分不能为空！',
        'picture.require'=>'营养餐的图片不能为空！',
        'nutrition.require'=>'营养成分不能为空！',
        'gym_id.require'=>'健身房编码不能为空！',
        'which_day.require'=>'您添加的营养餐是一周中的那一天?',
        'whitch_day.number'=>'星期内容必须为int类型'
      ]
    );
    //验证必填内容
    if(!$validate->check($inputData)){
          abort(0005,$validate->getError());
    }
    $dataObject = new self();
    if(!self::mealExists($inputData['gym_id'],$inputData['which_day'])){
      //进行添加操作
      $inputData['create_time'] = time();
      $inputData['last_update_time'] = time();
      $result = $dataObject->data($inputData)->allowField(true)->isUpdate(false)->save();
    }else{
      //直接进行修改操作
      $result = self::montify();
    }
    if(!$result){
      abort(-00010,'添加营养餐信息失败！');
    }
    db('nutritious_meal_history')->data([
        'ingredients'=>$inputData['ingredients'],
        'picture'=>$inputData['picture'],
        'nutrition'=>$inputData['nutrition'],
        'gym_id'=>$inputData['gym_id'],
        'which_day'=>$inputData['which_day'],
        'create_time'=>time(),
        'last_update_time'=>time(),
        ])->insert();
    return [];
  }

  public static function montify(){
    $allowField[] = 'ingredients'; //营养餐的成分
    $allowField[] = 'create_time'; //创建时间
    $allowField[] = 'last_update_time'; //最后更新时间
    $allowField[] = 'picture'; //图片内容
    $allowField[] = 'nutrition'; //营养成分
    $allowField[] = 'gym_id'; //健身房的编号
    $allowField[] = 'which_day';//一周中的哪一天
    $inputData = self::getInputData();
    $validate = new Validate(
      [
        'ingredients'=>'require',
        'picture'=>'require',
        'nutrition'=>'require',
        'gym_id'=>'require',
        'which_day'=>'require|number'
      ],
      [
        'ingredients.require'=>'营养餐的成分不能为空！',
        'picture.require'=>'营养餐的图片不能为空！',
        'nutrition.require'=>'营养餐的成分不能为空！',
        'gym_id.require'=>'健身房编码不能为空！',
        'which_day.require'=>'您添加的营养餐是一周中的那一天?',
        'which_day.number'=>'星期内容必须为int类型'
      ]
    );
    //验证必填内容
    if(!$validate->check($inputData)){
          abort(-0006,$validate->getError());
    }
    $dataObject =new self();
    $where['gym_id'] = $inputData['gym_id'];
    $where['which_day'] = $inputData['which_day'];
    $inputData['last_update_time'] = time();
    //对比两个数组的差距
    $response = self::info($where);
    $diff = array_diff_assoc($response[0],$inputData);
    unset($diff['id']);
    unset($diff['last_update_time']);
    unset($diff['create_time']);
    if(empty($diff)){
        abort(-20,'没有修改的内容！');
    }
    $result = $dataObject->allowField($allowField)->save($inputData,$where);
    if(!$result){
        abort(-0007,'修改信息失败！');
    }
    return true;
  }


  /**
   * [info 查询营养餐的内容]
   * @param  [integer] $limit [限制的行数]
   * @param  [integer] $page  [获取的页面]
   * @param  [array] $conditon [查询的条件]
   * @param  string $order [排序规则默认以创建时间进行排序]
   * @return [array]        [返回数组类型的内容]
   */
  public static function info($info){
    $where = ['gym_id'=>$info['gym_id']];
    if(array_key_exists('which_day',$info)){
        if(!empty($info['which_day'])){
            $where['which_day'] = $info['which_day'];
        }
    }
    $sqlQuery = self::sqlParams($info,['field'=>true,'order'=>'create_time desc','page'=>1,'limit'=>7]);
    $result = self::where($where)->field(true)->limit($sqlQuery['limit'])->page($sqlQuery['page'])->order($sqlQuery['order']);
    return self::infoOfCache($result);
  }

  /**
   * [mealToday 今天的餐食，如果健身房不存在餐食的话会返回空数组]
   * @return [array] [今天的餐食内容]
   */
  public static function mealToday($condition){
//      $condition['which_day'] = date('w',time()); //获取今天的星期日期
//      $condition['page'] = 1;
//      $condition['limit'] = 1;
      $response = self::info($condition); //设置搜索的内容
    return $response; //返回该健身房今天的营养餐食
  }

  /**
   * [mealExists 查询餐食是否存在]
   * @param  [integer] $gymId    [健身房的id]
   * @param  [integer] $whichDay [一周中的第几天]
   * @return [boolean]           [true|false]
   */
  protected static function mealExists($gymId,$whichDay){
      $where['gym_id'] = $gymId;
      $where['which_day'] = $whichDay;
      if(self::mealSum($where) > 0){
          return true;
      }
      return false;
  }


  /**
   * [mealSum 营养餐食统计]
   * @param  [array] $condition [数组类型的搜索内容]
   * @return [type]           [description]
   */
  public static function mealSum($condition){
      $gymId = $condition['gym_id'];
      $whichDay = $condition['which_day'];
      $where = ['gym_id'=>$gymId,'which_day'=>$whichDay];
      return self::where($where)->count();
  }
}
